﻿using EventMgrLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionRoc.Core;

namespace VisionRoc_Measure
{
    public partial class FormTcpServerTool : Form
    {
        TCPServer m_TCPServer;
        public FormTcpServerTool(TCPServer _TcpServer)
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景 
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲  
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.DoubleBuffered = true;//避免时间显示控件闪烁
            InitializeComponent();
            m_TCPServer = _TcpServer;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormTcpServerTool_Load(object sender, EventArgs e)
        {
            EventMgr.Ins.GetEvent<LogEvent>().Subscribe(LogHandle, log => log.SolutionName == "Main");  //接受外部发步的记录日志的事件
            m_TCPServer.ReadTCPServerParameter();
            if (m_TCPServer.State)
            {
                //Global.AddLogInfo(LogLevel.OK, "服务器已启动。");
                txt_IP.Text = m_TCPServer.IP;
                txt_Port.Text = m_TCPServer.Port.ToString();
                btn_StartServce.Enabled = false;
                btn_CloseSocket.Enabled = true;
                txt_IP.Enabled = false;
                txt_Port.Enabled = false;
            }
            else
            {
                //Global.AddLogInfo(LogLevel.Info, "服务器未启动。");
                txt_IP.Text = m_TCPServer.IP;
                txt_Port.Text = m_TCPServer.Port.ToString();
                btn_StartServce.Enabled = true;
                btn_CloseSocket.Enabled = false;
               
            }
        }

        /// <summary>
        /// 日志订阅时间函数
        /// </summary>
        /// <param name="obj"></param>
        private void LogHandle(LogPayload obj)
        {
            AddLogListView(obj.Level, obj.LogMessage);
        }


        /// <summary>
        /// 关闭服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CloseSocket_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPServer.ServerClose();
                btn_StartServce.Enabled = true;
                btn_CloseSocket.Enabled = false;
                txt_IP.Enabled = true;
                txt_Port.Enabled = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_StartServce_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPServer.IP = txt_IP.Text;
                m_TCPServer.Port = Convert.ToInt32(txt_Port.Text);
                m_TCPServer.StartSocketServer();
                btn_StartServce.Enabled = false;
                btn_CloseSocket.Enabled = true;
                txt_IP.Enabled = false;
                txt_Port.Enabled = false;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
       
        }

        private void btn_SendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                if(txt_Msg.Text.Trim().Length>0)
                {
                    m_TCPServer.Send(txt_Msg.Text.Trim());
                }
                else
                {
                    MessageBox.Show("发送至客户端消息不能为空！也不能有空格。");
                }
               
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        
        }

        /// <summary>
        /// 全程日志记录 不会报异常
        /// </summary>
        /// <param name="level"></param>
        /// <param name="Log"></param>
        public void AddLogListView(int level, string Log)
        {
            //日志显示控件记录 通过委托的方式 全部主线程记录 不会报跨线程异常
            this.Invoke(new Action(() =>
            {
                if (Global.LogCount > 0)
                {
                    //显示日志的显示数量 防止内存溢出
                    if (lstInfo.Items.Count >= Global.LogCount)
                    {
                        lstInfo.Items.RemoveAt(lstInfo.Items.Count - 1);
                    }

                    ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ffff"), level);
                    lst.SubItems.Add(Log);
                    //日志是从第一条插入 而不是从最后面追加
                    lstInfo.Items.Insert(0, lst);
                }
                else if (Global.LogCount < 0)
                {
                    ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ffff"), level);
                    lst.SubItems.Add(Log);
                    //日志是从第一条插入 而不是从最后面追加
                    lstInfo.Items.Insert(0, lst);
                }
            }));
        }
         
        /// <summary>
        /// 保存参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SaveParameter_Click(object sender, EventArgs e)
        {
            try
            {
                m_TCPServer.IP = txt_IP.Text;
                m_TCPServer.Port = Convert.ToInt32(txt_Port.Text);
                m_TCPServer.WriteTCPServerParameter();
                MessageBox.Show("保存成功.");
            }
            catch(Exception ex )
            {
                MessageBox.Show(ex.ToString());
            }
         
        }

        private void FormTcpServerTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            EventMgr.Ins.GetEvent<LogEvent>().Unsubscribe(LogHandle);
        }
    }
}
